package com.inossem.allotin.activity.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.inossem.allotin.R;
import com.inossem.allotin.adapter.BluetoothListAdapter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author 王斯宇
 * @time on 2019/7/8 15:01
 * @email siyu.wang@inossem.com
 */
public class BluetoothListActivity extends BlueToothBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    //    @BindView(R.id.bluetooth_device)
//    TextView bluetoothDevice;
    @BindView(R.id.status)
    TextView status;
    private BluetoothListAdapter adapter;
    private BluetoothAdapter mBluetoothAdapter;
    private static final int REQUEST_ENABLE_BT = 1;
    // 10秒后停止查找搜索.
    private static final long SCAN_PERIOD = 10000;
    private Handler mHandler;
    private boolean mScanning;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_list);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        //默认不弹出键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //强制横屏z
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        mHandler = new Handler();
        LinearLayoutManager manager = new LinearLayoutManager(BluetoothListActivity.this);
        recyclerView.setLayoutManager(manager);


        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "BLE is not supported", Toast.LENGTH_SHORT).show();
            finish();
        }

        // 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(BluetoothListActivity.this, "Bluetooth not supported.", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }

        // Initializes list view adapter.
        adapter = new BluetoothListAdapter(BluetoothListActivity.this);
        recyclerView.setAdapter(adapter);
        adapter.setListener((address, name) -> {
            Toast.makeText(BluetoothListActivity.this, "连接中", Toast.LENGTH_SHORT).show();
            setBuletoothScan(address, name, null);
//            setBuletoothScan(address, name, new OnBluetoothResuleListener() {
//                @Override
//                public void OnResuktListener(String result) {
//                    if (result.equals("true")) {
//                        finish();
//                    }
//                }
//            });

        });
        scanLeDevice(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    resetStatus("重新扫描");
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
//                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);
            mScanning = true;
            resetStatus("扫描中");
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            resetStatus("重新扫描");
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

    private void resetStatus(String message) {
        if (status != null) {
            status.setText(message);
        }
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            Log.i("aaa", "bluetooth === " + device.getName() + "-----" + device.getAddress());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.addDevice(device);
                }
            });
        }
    };

    @OnClick(R.id.status)
    public void onViewClicked() {
        if (!mScanning) {
            adapter.clear();
            scanLeDevice(true);
        }
    }
}
